<?php
declare (strict_types=1);

namespace app\video\model;

use app\common\model\BaseModel;
use app\common\self\MyJob;
use app\common\self\SelfRedis;
use app\mall\model\Activity;
use app\mall\model\Goods;
use app\user\model\UserFollow;
use app\user\model\UserVideoFollow;
use app\user\model\UserVideoProfit;
use think\Model;

use app\user\model\User;
use think\Db;
use think\Request;

class Video extends BaseModel
{
    public $field = 'id,uid,type,relation_id,title,cover,video,likes,shares,comments,add_time,sort,is_hot,log_id,position';

    // 默认查询值
    public $defaultWhere = [
        ['is_check', '=', 1], // 审核通过
        ['is_delete', '=', 0] // 存在的
    ];

    //    预处理数据处理
    public function getCoverAttr($value)
    {
        //return env('app.host_domin').'://'.$_SERVER['HTTP_HOST'].$value;
        if (checkFile($value))
            return getApiDominUrl($value);
        return getHostDominUrl($value);
    }


//    预处理数据处理
    public function getVideoAttr($value)
    {
        //return env('app.host_domin').'://'.$_SERVER['HTTP_HOST'].$value;
//        return env('app.host_domin').'://'.env('app.static_host').$value;
        if (checkFile($value))
            return getApiDominUrl($value);
        return getHostDominUrl($value);
    }

    public function getTitleAttr($value)
    {
        return emojiDecode($value);
    }

    // 视频-获取列表操作
    public function getList($get)
    {
        $type = isset($get['type']) ? $get['type'] : 0;
        $oredr = 'sort desc';
        $where = [
            ['status', '=', 1], // 状态1
            ['is_check', '=', 1], // 审核通过
            ['is_delete', '=', 0] // 存在的
        ];
        $whereOr = [];
        $is_hot = isset($get['is_hot']) ? $get['is_hot'] : -1;
        // 是否为首页视频 推荐视频
        if ($is_hot >= 0 && !isset($get['title']) && $is_hot == 1)
            $where[] = ['is_hot', '=', $is_hot];

        // 分类
        if ($type && $type >= 1)
            $where[] = ['type_id', '=', $type];
        // 搜索 title ,视频名称 和 用户昵称
        if (isset($get['title']) && $get['title'] && trim($get['title'])) {
            $whereOr = [
                [['title', 'like', trim($get['title']) . '%']],
                [['user_nick_name', 'like', trim($get['title']) . '%']]
            ];
        }

        $field = 'id,title,cover,video,likes,shares,comments,add_time,uid,is_hot,position';
        $this->queryList($get, $field, $where, $oredr, $whereOr);
        foreach ($this->modelList as $k => $v) {
            $this->list['data'][$k]['user_nickname'] = isset($v->oneUser->nickname) ? $v->oneUser->nickname : '风再起时';
            $this->list['data'][$k]['user_avatarurl'] = isset($v->oneUser->avatarurl) ? getHostDominUrl($v->oneUser->avatarurl) : 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/icon/%E7%BC%96%E7%BB%84%205%402x.png';
            $this->list['data'][$k]['cover'] = getHostDominUrl($v->cover);
//            if($this->list['data'][$k]['is_hot'] != $is_hot)
//                unset($this->list['data'][$k]);
        }
        $isRefresh = isset($get['isRefresh']) ? $get['isRefresh'] : 0;
        if ($isRefresh && $isRefresh == 1) shuffle($this->list['data']);
    }

    /**
     * 切换上下条记录，默认是下一条
     */
    public function getSlideOne($request)
    {
        // 排序字段值-默认为时间，排序值
        //$orderType = $request->get('orderType','add_time');
        $orderType = $request->param('orderType', 'id');
        //$val = $request->get('val',false);
        $val = $request->param('id', false);
        $order = $request->param('order', '>');
        $type = $request->param('type', 0);
//        $is_hot = $request->get('is_hot',0);
        // 判断开始
        if (!$val)
            return retu_json(400, '值不得为空');
        if (!$order || !in_array($order, ['>', '<']))
            return retu_json(400, '值只能为大于或者等于');
        /*
        if(!$orderType || !in_array($orderType,['add_time']))
            return retu_json(400,'排序字段值错误');
        */
        // 分类
        if ($type && $type >= 1)
            $this->defaultWhere[] = ['type_id', '=', $type];
        // 推荐
//        $this->defaultWhere[] = ['is_hot','=',$is_hot];
        $one = $this->where(array_merge($this->defaultWhere, [[$orderType, $order, $val]]))->order('id' . ($order == '>' ? ' asc' : ' desc'))->field($this->field)->find();

        // 如果没有视频 那么重新拿取到相反的第一条数据
        if (!$one) {
            $more = $this->where($this->defaultWhere)->order($orderType . ($order == '>' ? ' asc' : ' desc'))->field($this->field)->find(); // ->select()->toArray()
            $ddd = $this->getRelated($more);
            $list222 = $ddd->toArray();
            $list222['user_nickname'] = $ddd->oneUser->nickname;
            $list222['user_avatarurl'] = $ddd->oneUser->avatarurl;
            return ['list' => $list222, 'msg' => '初始化视频33333'];
        } else {
            $more = $this->getRelated($one);
            $listOne = $more->toArray();
            $listOne['user_nickname'] = $more->oneUser->nickname;
            $listOne['user_avatarurl'] = $more->oneUser->avatarurl;
            return ['list' => $listOne, 'msg' => '视频加载' . ($order == '>' ? '下一条' : '上一条') . '成功1111,user_id:']; //.$this->user->id.',当前id:'.$more->id
        }

    }

    /**
     * 拿取三条数据
     */
    public function getNewList($request)
    {
        $id = $request->param('id', 0);
        $type = $request->param('type', 0);
        $is_hot = $request->param('is_hot', 0);
        $limit = $request->param('limit', 3);

        $orderType = $request->param('orderType', 'add_time');
        $val = $request->param('val', false);
        $order = '>';
        //$order = $request->get('order','>');
        if (!$id || $id - 0 <= 0)
            return retu_json(400, '列表记录为111空' . $id);
        if ($type && $type > 0)
            $this->defaultWhere[] = ['type_id', '=', $type];
        if ($is_hot && $is_hot > 0 && $is_hot != 2)
            $this->defaultWhere[] = ['is_hot', '=', $is_hot];
        if ($limit > 3)
            $limit = 3;
        if (!$oneModel = $this->find($id))
            return retu_json(400, '没有该记录');

        $count = $this->where($this->defaultWhere)->field($this->field)->count();
        if ($count <= 3) {
            $list = $this->where($this->defaultWhere)->field($this->field)->select();
            $allList = [];
            foreach ($list as $item) {
                $item['user_nickname'] = $item->oneUser->nickname ?? '联我';
                $item['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                $item = $this->getRelated($item);
                unset($item['oneUser']);
                $allList[] = $item;
            }
            return ['no_loop' => true, 'list' => $allList];
        }


        $list = $this->getRelated($oneModel);
        $list = $list->toArray();
        $list['user_nickname'] = $oneModel->oneUser->nickname ?? '联我';
        $list['user_avatarurl'] = $oneModel->oneUser->avatarurl ?? '';
        //return $list;
        /**
         * ***********************   拿取上两条数据开始  ***********************
         */

        // 拿取上条数据
        $lastWhere = $this->defaultWhere;
        $lastWhere[] = ['id', '<', $id];
        $lastModel = $this->where($lastWhere)->order($orderType . ' desc')->field($this->field)->find();
        // 如果没有数据
        if (!$lastModel) {
            $Where = $this->defaultWhere;
            $Where[] = [$orderType, $order, $oneModel->add_time];
            $lastModel = $this->where($this->defaultWhere)->order('id' . ($order == '>' ? ' desc' : ' asc'))->field($this->field)->find();
            $lastModel['user_nickname'] = $lastModel->oneUser->nickname ?? '';
            $lastModel['user_avatarurl'] = $lastModel->oneUser->avatarurl ?? '';
            $lastModel = $this->getRelated($lastModel);
            unset($lastModel['oneUser']);
            // 有一条数据
        } else if ($lastModel) {
            $lastModel['user_nickname'] = $lastModel->oneUser->nickname ?? '';
            $lastModel['user_avatarurl'] = $lastModel->oneUser->avatarurl ?? '';
            $lastModel = $this->getRelated($lastModel);
            unset($lastModel['oneUser']);
        }
        /**
         * ***********************   结束  ***********************
         */

        /**
         * ***********************   拿取下两条数据开始  ***********************
         */
        // 拿取下条数据
        $nextWhere = $this->defaultWhere;
        $nextWhere[] = ['id', '>', $id];
        $nextModel = $this->where($nextWhere)->order($orderType . ' asc')->field($this->field)->find();
        // 如果没有数据
        if (!$nextModel) {
            $Where = $this->defaultWhere;
            $Where[] = [$orderType, $order, $oneModel->add_time];
            $nextModel = $this->where($this->defaultWhere)->order('id' . ($order == '<' ? ' desc' : ' asc'))->field($this->field)->find();
            $nextModel['user_nickname'] = '哈哈农夫';
            $nextModel['user_avatarurl'] = 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/icon/%E7%BC%96%E7%BB%84%205%402x.png';
            # 如果有对应的用户
            if ($nextModel->oneUser) {
                $nextModel['user_nickname'] = $nextModel->oneUser->nickname;
                $nextModel['user_avatarurl'] = $nextModel->oneUser->avatarurl;
            }
            $nextModel = $this->getRelated($nextModel);
            unset($nextModel['oneUser']);
            // 有一条数据
        } else if ($nextModel) {
            $nextModel['user_nickname'] = $nextModel->oneUser->nickname ?? '';
            $nextModel['user_avatarurl'] = $nextModel->oneUser->avatarurl ?? '';
            $nextModel = $this->getRelated($nextModel);
            unset($nextModel['oneUser']);
        }
        return [
            'no_loop' => false,
            'list' => [$lastModel, $list, $nextModel]
        ];
    }

    /**
     * 单条记录
     */
    public function oneLimit($request)
    {
        $id = $request->param('id', 0);
        if (!$oneModel = $this::where(['status' => 1, 'is_delete' => 0])->find($id))
            return retu_json(400, '没有该记录');
        $list = $this->getRelated($oneModel);
        $list = $list->toArray();
        return $list;
    }

    /**
     * @param $id 查询当前id，并进行判断数据范湖
     * @return array|null|Model|void 返回当前记录
     */
    public function getOne($request)
    {
        $id = $request->param('id', 0);
        $type = $request->param('type', 0);
        $is_hot = $request->param('is_hot', 0);
        $limit = $request->param('limit', 3);

        $orderType = $request->param('orderType', 'add_time');
        $val = $request->param('val', false);
        $order = '>';
        //$order = $request->get('order','>');

        if (!$id || $id <= 0)
            return retu_json(400, '列表记录为空');
        if ($type && $type > 0)
            $this->defaultWhere[] = ['type_id', '=', $type];
        if ($is_hot && $is_hot > 0 && $is_hot != 2)
            $this->defaultWhere[] = ['is_hot', '=', $is_hot];
        if ($limit > 3)
            $limit = 3;
        if (!$oneModel = $this->find($id))
            return retu_json(400, '没有该记录');
        $list = $this->getRelated($oneModel);
        $list = $list->toArray();
        $list['user_nickname'] = $oneModel->oneUser->nickname ?? '';
        $list['user_avatarurl'] = $oneModel->oneUser->avatarurl ?? '';
        //return $list;
        /**
         * ***********************   拿取上两条数据开始  ***********************
         */
        // 拿取上两条数据
        $lastWhere = $this->defaultWhere;
        $lastWhere[] = ['add_time', '<', $oneModel->add_time];
        $lastModel = $this->where($lastWhere)->order($orderType . ' desc')->limit(2)->field($this->field)->select();
        $lastList = [];
        // 如果没有数据
        if (!$lastModel || count($lastModel) == 0) {
            $Where = $this->defaultWhere;
            $Where[] = [$orderType, $order, $oneModel->add_time];
            $lastModel = $this->where($this->defaultWhere)->order($orderType . ($order == '>' ? ' desc' : ' asc'))->limit(2)->field($this->field)->select();
            foreach ($lastModel as $item) {
                $item['user_nickname'] = $item->oneUser->nickname ?? '';
                $item['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                $item = $this->getRelated($item);
                unset($item['oneUser']);
                $lastList[] = $item->toArray();
            }
            $lastList = [
                $lastList[1],
                $lastList[0]
            ];
            // 有一条数据
        } else if (count($lastModel) == 1) {
            $Where = $this->defaultWhere;
            $Where[] = [$orderType, $order, $oneModel->add_time];
            $lastMo = $this->where($this->defaultWhere)->order($orderType . ($order == '>' ? ' desc' : ' asc'))->limit(1)->field($this->field)->find();
            $lastModel[0]['user_nickname'] = $lastModel[0]->oneUser->nickname ?? '';
            $lastModel[0]['user_avatarurl'] = $lastModel[0]->oneUser->avatarurl ?? '';
            $lastModel[0] = $this->getRelated($lastModel[0]);
            unset($lastModel[0]['oneUser']);
            $lastMo['user_nickname'] = $lastMo->oneUser->nickname ?? '';
            $lastMo['user_avatarurl'] = $lastMo->oneUser->avatarurl ?? '';
            $lastMo = $this->getRelated($lastMo);
            unset($lastMo['oneUser']);
            $lastList = [
                $lastModel[0]->toArray(), $lastMo->toArray()
            ];
        } else {
            foreach ($lastModel as $item) {
                $item['user_nickname'] = $item->oneUser->nickname ?? '';
                $item['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                $item = $this->getRelated($item);
                unset($item['oneUser']);
                $lastList[] = $item->toArray();
            }
            $lastList = [
                $lastList[1],
                $lastList[0]
            ];
        }
        /**
         * ***********************   结束  ***********************
         */
//        dump($lastList);
//        exit;
        /**
         * ***********************   拿取下两条数据开始  ***********************
         */
        // 拿取下两条数据
        $nextWhere = $this->defaultWhere;
        $nextWhere[] = ['add_time', '>', $oneModel->add_time];
        $nextModel = $this->where($nextWhere)->order($orderType . ' asc')->limit(2)->field($this->field)->select();
        $nextList = [];
        // 如果没有数据
        if (!$nextModel || count($nextModel) == 0) {
            $Where = $this->defaultWhere;
            $Where[] = [$orderType, $order, $oneModel->add_time];
            $nextModel = $this->where($this->defaultWhere)->order($orderType . ($order == '<' ? ' desc' : ' asc'))->limit(2)->field($this->field)->select();
            foreach ($nextModel as $item) {
                $item['user_nickname'] = $item->oneUser->nickname ?? '';
                $item['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                $item = $this->getRelated($item);
                unset($item['oneUser']);
                $nextList[] = $item->toArray();
            }
            // 有一条数据
        } else if (count($nextModel) == 1) {
            $Where = $this->defaultWhere;
            $Where[] = [$orderType, $order, $oneModel->add_time];
            $nextMo = $this->where($this->defaultWhere)->order($orderType . ($order == '<' ? ' desc' : ' asc'))->limit(1)->field($this->field)->find();
            $nextModel[0]['user_nickname'] = $nextModel[0]->oneUser->nickname ?? '';
            $nextModel[0]['user_avatarurl'] = $nextModel[0]->oneUser->avatarurl ?? '';
            $nextModel[0] = $this->getRelated($nextModel[0]);
            unset($nextModel[0]['oneUser']);
            $nextMo['user_nickname'] = $nextMo->oneUser->nickname ?? '';
            $nextMo['user_avatarurl'] = $nextMo->oneUser->avatarurl ?? '';
            $nextMo = $this->getRelated($nextMo);
            unset($nextMo['oneUser']);
            $nextList = [
                $nextModel[0]->toArray(), $nextMo->toArray()
            ];
        } else {
            foreach ($nextModel as $item) {
                $item['user_nickname'] = $item->oneUser->nickname ?? '';
                $item['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                $item = $this->getRelated($item);
                unset($item['oneUser']);
                $nextList[] = $item->toArray();
            }
        }
        unset($oneModel['oneUser']);
        return [
            $lastList[0],
            $lastList[1],
            $oneModel->toArray(),
            $nextList[0],
            $nextList[1]
        ];

        /**
         * ***********************   结束  ***********************
         */
        return [
            'last' => isset($lastModel) ? $this->getRelated($lastModel) : [],
            'now' => isset($oneModel) ? $this->getRelated($oneModel) : [],
            'next' => isset($nextModel) ? $this->getRelated($nextModel) : []
        ];
    }

    /**
     * 获取到视频对应关联的商品或者活动信息
     */
    public function getRelated($oneModel)
    {
        $oneModel['is_follow'] = false;
        $oneModel['is_likes'] = false;
        // 如果有登录  则 进行 显示 是否有互相关注 且查看者  不是 本人
        if (isset($this->user) && $this->user) {
            //  视频发布者的id 用户的id  ---  是否关注
            if ($this->user->id != $oneModel->uid)
                $oneModel['is_follow'] = UserFollow::where(['fans_id' => $this->user->id, 'uid' => $oneModel->uid])->count() > 0;

            // 是否喜欢视频
            $oneModel['is_likes'] = UserVideoFollow::where(['uid' => $this->user->id, 'vid' => $oneModel->id, 'status' => 1])->count() > 0;
        }
        //类型为1 如果是商品id
        if ($oneModel['type'] == 1) {
            /*
            if($oneModel->getModelGoods)
                return retu_json(400,'此商品不存在');
            // 拿取到商品信息
            $oneModel['goods'] = $oneModel->getFieldData([$oneModel->getModelGoods->toArray()],'id,title,name,cover,share,default_price,default_discount_price');
            unset($oneModel->getModelGoods);
             */
            if ($oneModel->getModelGoods) {
                $oneModel['goods'] = $oneModel->getFieldData([$oneModel->getModelGoods->toArray()], 'id,title,name,cover,share,default_price,default_discount_price');
                unset($oneModel->getModelGoods);
            }
        } else {
            /*
            if(!$oneModel->getModelActivity)
                return retu_json(400,'此活动不存在');
            if($oneModel->getModelActivity->status == 0)
                return retu_json(400,'活动已下架');
            $oneModel['activity'] = $oneModel->getFieldData([$oneModel->getModelActivity->toArray()],'id,name,cover,hours,title,share,num,content');
            unset($oneModel->getModelActivity);
             */
            if ($oneModel->getModelActivity && $oneModel->getModelActivity->status != 0) {
                $oneModel['activity'] = $oneModel->getFieldData([$oneModel->getModelActivity->toArray()], 'id,name,cover,hours,title,share,num,content');
                unset($oneModel->getModelActivity);
            }
        }
        return $oneModel;
    }

    /**
     * @param $id 查询当前id，并进行判断数据范湖
     * @return array|null|Model|void 返回当前记录
     */
    public function newGetOne($request)
    {
        $id = $request->param('id', 0);
        $type = $request->param('type', 0);
        $is_hot = $request->param('is_hot', 0);
        $limit = $request->param('limit', 3);

        $orderType = $request->param('orderType', 'add_time');
        $val = $request->param('id', false);
//        $order = '>';
        $order = $request->param('order', '>');

        if (!$id || $id <= 0)
            return retu_json(400, '列表记录为空');
        if ($type && $type > 0)
            $this->defaultWhere[] = ['type_id', '=', $type];
        if ($is_hot && $is_hot > 0)
            $this->defaultWhere[] = ['is_hot', '=', $is_hot];
        if ($limit > 3)
            $limit = 3;
//        if(!$oneModel = $this->find($id))
//            return retu_json(400,'没有该记录');
//        $list = $this->getRelated($oneModel);
//        $list = $list->toArray();
//        $list['user_nickname'] = $oneModel->oneUser->nickname;
//        $list['user_avatarurl'] = $oneModel->oneUser->avatarurl;
        //return $list;
        /**
         * ***********************   拿取上两条数据开始  ***********************
         */
        // 拿取上两条数据
        $lastWhere = $this->defaultWhere;
//        $lastWhere[] = ['add_time',$order,$oneModel->add_time];
        $lastWhere[] = ['id', $order, $val];

        $lastModel = $this->where($lastWhere)->order('id' . ($order == '<' ? ' desc' : ' asc'))->limit(3)->field($this->field)->select();
        if (count($lastModel) == 3) {
            $all = [];
            foreach ($lastModel as $item) {
                $item['user_avatarurl'] = $item->oneUser->avatarurl;
                $item = $this->getRelated($item);
                unset($item['oneUser']);
                $all[] = $item->toArray();
            }
            return $all;
        }

//        dump($lastModel->toArray());
//        exit;
        $lastList = [];
        // 如果没有数据
        if (!$lastModel || count($lastModel) == 0) {
            $Where = $this->defaultWhere;
            //$Where[] = [$orderType,$order,$oneModel->add_time];
            $lastWhere[] = ['id', $order, $val];
            $lastModel = $this->where($this->defaultWhere)->order('id' . ($order == '<' ? ' desc' : ' asc'))->limit(3)->field($this->field)->select();
            $this->where($this->defaultWhere)->order('id' . ($order == '<' ? ' desc' : ' asc'))->limit(3)->field($this->field)->select();
            foreach ($lastModel as $item) {
                $item['user_nickname'] = $item->oneUser->nickname ?? '';
                $item['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                $item = $this->getRelated($item);
                unset($item['oneUser']);
                $lastList[] = $item->toArray();
            }
//            $lastList = [
//                $lastList[2],
//                $lastList[1],
//                $lastList[0],
//            ];
            return '<' == $order ? [
                $lastList[0],
                $lastList[1],
                $lastList[2]
            ] : [
                $lastList[0],
                $lastList[1],
                $lastList[2],
            ];


//            return $lastList;
            // 有一条数据
        } else if (count($lastModel) == 1) {
            $Where = $this->defaultWhere;
//            $Where[] = [$orderType,$order,$oneModel->add_time];
            $lastWhere[] = ['id', $order, $val];
            $lastMo = $this->where($this->defaultWhere)->order('id' . ($order == '<' ? ' desc' : ' asc'))->limit(2)->field($this->field)->select();
            foreach ($lastMo as $k => $item) {
                $lastMo[$k]['user_nickname'] = $item->oneUser->nickname ?? '';
                $lastMo[$k]['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                $lastMo[$k] = $this->getRelated($item);
                unset($lastMo[$k]['oneUser']);
            }
            return '<' == $order ? [
                $this->getRelated($lastModel[0]),
                $lastMo[0],
                $lastMo[1]
            ] : [
                $this->getRelated($lastModel[0]),
                $lastMo[0],
                $lastMo[1],
            ];


            // 有两条 数据
        } else if (count($lastModel) == 2) {
            $Where = $this->defaultWhere;
//            $Where[] = [$orderType,$order,$oneModel->add_time];
            $lastWhere[] = ['id', $order, $val];
            $lastMo = $this->where($this->defaultWhere)->order('id' . ($order == '<' ? ' desc' : ' asc'))->field($this->field)->find();
            foreach ($lastModel as $k => $item) {
                $lastModel[$k]['user_nickname'] = $item->oneUser->nickname ?? '';
                $lastModel[$k]['user_avatarurl'] = $item->oneUser->avatarurl ?? '';
                unset($lastModel[$k]['oneUser']);
                $lastModel[$k] = $this->getRelated($item);
            }
            $lastMo['user_nickname'] = $lastMo->oneUser->nickname ?? '';
            $lastMo['user_avatarurl'] = $lastMo->oneUser->avatarurl ?? '';
            unset($lastMo['oneUser']);
            return '<' == $order ? [
                $lastModel[0],
                $lastModel[1],
                $this->getRelated($lastMo),
            ] : [
                $lastModel[0],
                $lastModel[1],
                $this->getRelated($lastMo),
            ];
        }
        return [
        ];
    }

    /**
     * 根据活动拿取到对应的商品id
     */
    public function getVideo($videoId)
    {
        $videoModel = $this->find($videoId);
        if (!$videoModel)
            return ['code' => 400, 'msg' => '当前视频记录不存在'];
        if ($videoModel->status != 1)
            return ['code' => 400, 'msg' => '该视频没有上架'];
        if ($videoModel->is_check != 1)
            return ['code' => 400, 'msg' => '审核状态错误'];
        $this->getRelated($videoModel);
        return ['code' => 200, 'model' => $videoModel];
    }

    /**
     * 一对一关联
     */
    public function oneUser()
    {
//        $list = $this->find(1);
//        dump($list->user->nickname);
//        exit;
        // 父user  id  ，  当前字段的id
        return $this->hasOne(User::class, 'id', 'uid');
    }

    /**
     * 一对一关联 此处获取到商品id
     */
    public function getModelGoods()
    {
        // 关联商品表goods  商品表goods的id  ，  当前关联字段名称
        return $this->hasOne(Goods::class, 'id', 'relation_id');
    }

    /**
     * 一对一关联 此处获取到活动id
     */
    public function getModelActivity()
    {
        // 关联活动表  活动表的id  ，  当前关联字段名称
        return $this->hasOne(Activity::class, 'id', 'relation_id');
    }

    /*
     一对多关联
     $list->comments // 查询单条记录
    // 按照条件查询
    dump($list->comments()->where('id',1)->select()->toArray());
    //  一对多关联
    public function comments()
    {
        return $this->hasMany(User::class,'id','uid');
    }
    */


    /*
     * 获取我的视频头部数据
     * return 作品数 喜欢数 获得点赞数
     */
    public function getLikeNum($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $where = [['uid', '=', $id], ['is_delete', '=', 0]];
            $field = "count(id) as my_video_number,IFNULL(sum(likes), 0) as my_like_number";
            $data = $this->where($where)->field($field)->find();
            return $data;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 获取我的视频点赞数
     */
    public function getVideoLikeNum($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $where = ['uid' => $id, 'is_delete' => 0];
            $data = $this->field("sum(likes) as like_number")->where($where)->find();
            return !empty($data['like_number']) ? $data['like_number'] : 0;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 获取用户视频列表
     */
    public function getUserVideos($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $where = [['uid', '=', $id], ['add_time', '>', 0], ['is_delete', '=', 0]];
            $limit = isset($data['limit']) && !empty($data['limit']) ? $data['limit'] : 15;//每页显示数据
            $query = ['page' => (isset($data['page']) ? $data['page'] : 1)];//分页参数
            $field = 'id,title,cover,video,likes,views,is_check,add_time';
            $item = $this->where($where)->field($field)->order('add_time desc')->paginate($limit, false, ['query' => $query]);
            $list = empty($item) ? [] : $item->toArray();
            if (!empty($list['data'])) {
                $year = date('Y', time());
                foreach ($list['data'] as $k => $v) {
                    /*if($v['is_check']==1){
                        $list['data'][$k]['is_check'] = '已发布';
                    }elseif($v['is_check']==2){
                        $list['data'][$k]['is_check'] = '未通过';
                    }else{
                        $list['data'][$k]['is_check'] = '审核中';
                    }*/
                    $list['data'][$k]['title'] = emojiDecode($v['title']);
                    if ($year == date('Y', $v['add_time'])) $list['data'][$k]['add_time'] = date('n月j日', $v['add_time']);
                    else $list['data'][$k]['add_time'] = date('Y年n月j日', $v['add_time']);
                }
            }
            return $list;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 用户视频主页
     */
    public function videoHome()
    {
        try {
            $data = Input('post.');
            if (empty($data['uid'])) exception('找不到该用户!');
            $where = ['uid' => $data['uid'], 'is_delete' => 0];
            $limit = isset($data['limit']) && !empty($data['limit']) ? $data['limit'] : 15;//每页显示数据
            $query = ['page' => (isset($data['page']) ? $data['page'] : 1)];//分页参数
            $field = 'id,title,cover,video,likes,views,add_time';
            $item = $this->where($where)->field($field)->order('add_time desc')->paginate($limit, false, ['query' => $query]);
            $list = empty($item) ? [] : $item->toArray();
            if (!empty($list['data'])) {
                $year = date('Y', time());
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['title'] = emojiDecode($v['title']);
                    if ($year == date('Y', $v['add_time'])) $list['data'][$k]['add_time'] = date('n月j日', $v['add_time']);
                    else $list['data'][$k]['add_time'] = date('Y年n月j日', $v['add_time']);
                }
            }
            return $list;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 用户删除视频
     */
    public function delVideo($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if (empty($data['vid'])) exception('请选择视频!');
            $where = ['id' => $data['vid'], 'uid' => $id, 'is_delete' => 0];
            $field = 'id,title,is_check';
            $ret = $this->where($where)->field($field)->find();
            if (!empty($ret)) {
                if ($ret['is_check'] == 1) exception('不能删除已发布视频!');
                else {
                    if ($this->where(['id' => $ret['id']])->update(['is_delete' => 1])) return true;
                    else exception('删除视频失败!');
                }
            }
            exception('找不到该视频!');
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 用户发布视频
     */
    public function publishVideoLog($user)
    {
        try {
            if (empty($user->id)) exception('找不到该用户!');
            $data = Input('post.');
            if (empty($data['id'])) exception('请先选择要发布的视频!');
            if (empty($data['title'])) exception('请填写视频标题!');
            if (empty($data['type_id'])) exception('请选择视频分类!');
            if (empty($data['position'])) $data['position'] = '';
            if (!$infos = $this->where(['id' => $data['id']])->find()) exception('视频记录丢失，请重试!');
            $tid = 0;
            $lid = 0;
            if ($data['type'] == 2) {
                if (empty($data['aid']) || empty($data['log_id'])) exception('请选择要分享的活动!');
                if (!is_numeric($data['aid']) || !is_numeric($data['log_id'])) exception('请选择要分享的商品!');
                $tid = $data['aid'];
                $lid = $data['log_id'];
            } elseif ($data['type'] == 1) {
                if (empty($data['gid'])) exception('请选择要分享的商品!');
                if (!is_numeric($data['gid'])) exception('请选择要分享的商品!');
                $tid = $data['gid'];
            }//else  exception('请选择分享的类型!');
            $info = [
                'uid' => $user->id,
                'type' => $data['type'],
                'title' => emojiEncode($data['title']),
                'type_id' => $data['type_id'],
                'relation_id' => $tid,
                'log_id' => $lid,
                'position' => $data['position'],
                'add_time' => time(),
            ];
            if ($this->where(['id' => $data['id']])->update($info)) {
                $arrs = $infos->getData();
                $file_video = app()->getRootPath() . "public" . $arrs['video'];
                // fileLog('111---视频路劲：'.$file_video,'测试测试.log');
                $cos_path_video = strstr($arrs['video'], "/video/");
                // fileLog('111---视频上传后的路劲：'.$cos_path_video,'测试测试.log');
                $video_sql = strstr($arrs['video'], "/video/");
                // fileLog('111---视频sql的路劲：'.$video_sql,'测试测试.log');
                // 视频推送
                $queue = [
                    'file' => $file_video,
                    'cos_path' => $cos_path_video,
                    'id' => $data['id'],
                    'table' => serialize($this),
                    'data' => [
                        'video' => 'https://admin-miaomeimei-1301812909.cos.ap-guangzhou.myqcloud.com' . $video_sql
                    ]
                ];
                // fileLog('111---视频开始推送了','测试测试.log');
                $v = MyJob::pushQueue('FileUploadsJob', $queue, 10);
                // fileLog('111---视频推送已完成'.$v,'测试测试.log');
                // 图片推送
                $queueImg = [
                    'file' => app()->getRootPath() . "public" . $arrs['cover'],
                    'cos_path' => strstr($arrs['cover'], "/video/"),
                    'id' => $data['id'],
                    'table' => serialize($this),
                    'data' => [
                        'cover' => 'https://admin-miaomeimei-1301812909.cos.ap-guangzhou.myqcloud.com' . strstr($arrs['cover'], "/video/")
                    ]
                ];
                $vImg = MyJob::pushQueue('FileUploadsJob', $queueImg, 10);
                fileLog(date('y-m-d H:i:s') . '----推送中' . $v . "---------" . $vImg, '用户上传视频列表记录.log');
                return true;
            }
            exception('视频发布失败!');
            return false;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 用户上传视频文件
     */
    public function publishVideo($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if (!empty($_FILES['video'])) {
                if (empty($data['type'])) exception('请选择上传文件类型!');
                $m = date('Ym'); //按月份分目录
                $path = 'video/' . $m;
                $dir = app()->getRootPath() . 'public/uploads/video/' . $m . '/';
                if (!is_dir($dir)) @mkdir($dir, 0777); //目录不存在则创建
                $videoInfo = imgUpdate('video', $path, "video_{$id}_" . date('YmdHis'));
                if (!isset($videoInfo['result'])) exception($videoInfo['msg']);
                //获取视频第一帧画面生成图片并保存到数据库  参数1-文件地址，2-生成图片名，3-存储文件夹，4-第几秒画面，5-宽高
                $img = getVideoCover(app()->getRootPath() . 'public' . $videoInfo['result'], "images_{$id}_" . date('YmdHis') . ".jpeg", '/uploads/video/', 3, 0);
                $img = !empty($img) ? $img : 0;
                if ($vid = $this->insertGetId(['uid' => $id, 'title' => 0, 'status' => 0, 'cover' => $img, 'video' => $videoInfo['result']])) {
                    $v = MyJob::pushQueue('VideoDelayJob', ['id' => $vid], 7200);
                    fileLog('推送日志ok---' . $v, 'videoUploadsUser.log');
                    return ['id' => $vid, 'video' => getApiDominUrl($videoInfo['result']), 'cover' => !empty($img) ? getApiDominUrl($img) : ''];
                } else {
                    unlink(app()->getRootPath() . 'public' . $videoInfo['result']);//删除文件
                    !empty($img) ? unlink(app()->getRootPath() . 'public' . $img) : '';//删除文件
                    exception('上传失败，重稍后重试!');
                }
            }
            exception('上传失败，找不到上传的文件!');
            return false;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 用户上传视频图片
     */
    public function publishVideoImg($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if (empty($data['id'])) exception('找不到视频记录!');
            $info = $this->where(['id' => $data['id']])->find();
            if (empty($info)) exception('找不到视频记录!');
            if (!empty($_FILES['img'])) {
                if (empty($data['type'])) exception('请选择上传文件类型!');
                if (!empty($info['cover']) && file_exists(app()->getRootPath() . 'public' . $info['cover'])) {
                    unlink(app()->getRootPath() . 'public' . $info['cover']);//删除文件
                }
                $m = date('Ym'); //按月份分目录
                $path = 'video/' . $m . '_img';
                $dir = app()->getRootPath() . 'public/uploads/video/' . $m . '_img/';
                if (!is_dir($dir)) @mkdir($dir, 0777); //目录不存在则创建
                $imgInfo = imgUpdate('img', $path, "images_{$id}_" . date('YmdHis'));
                if (!isset($imgInfo['result'])) exception($imgInfo['msg']);
                if ($this->where(['id' => $info['id']])->update(['cover' => $imgInfo['result']]))
                    return ['id' => $info['id'], 'cover' => getApiDominUrl($imgInfo['result'])];
                else {
                    unlink(app()->getRootPath() . 'public' . $imgInfo['result']);//删除文件
                    exception('上传失败，重稍后重试!');
                }
            }
            exception('上传失败，找不到上传的文件!');
            return false;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 用户上传视频详情
     */
    public function publishVideoInfo($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if (!empty($_FILES['video'])) {
                if (empty($data['type'])) exception('请选择上传文件类型!');
                $imgInfo = imgUpdate('video', 'video', "video_{$id}_" . date('YmdHis'));
                if (!isset($imgInfo['result'])) exception($imgInfo['msg']);
                if ($vid = $this->insertGetId(['uid' => $id, 'title' => 0, 'status' => 0, 'cover' => 0, 'video' => $imgInfo['result']]))
                    return ['id' => $vid, 'video' => getApiDominUrl($imgInfo['result'])];
                else {
                    unlink('.' . $imgInfo['result']);//删除文件
                    exception('上传失败，重稍后重试!');
                }
            }
            exception('上传失败，找不到上传的文件!');
            return false;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 用户删除视频文件
     */
    public function delVideoFile($id)
    {
        try {
            if (empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if (empty($data['vid'])) exception('无效的视频id!');
            $info = Db::name('video')->where(['id' => $data['vid'], 'status' => 0, 'is_check' => 0])->find();
            if (empty($info)) exception('找不到视频记录!');
            if (!empty($info['video']) && file_exists(app()->getRootPath() . 'public' . $info['video'])) {
                if (unlink(app()->getRootPath() . 'public' . $info['video'])) {#删除视频文件
                    if (!empty($info['cover']) && file_exists(app()->getRootPath() . 'public' . $info['cover'])) {
                        unlink(app()->getRootPath() . 'public' . $info['cover']);#删除图片文件
                    }
                    $this->where(['id' => $info['id']])->delete();
                    return true;
                } else exception('删除失败!');
            }
            exception('无效的视频地址');
            return true;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 新增观看视频记录
     */
    public function addWatchRecord($user)
    {
        try {
            $data = Input('post.');
            if (empty($data['vid'])) exception('无效的视频id!');
            $info = $this->where(['id' => $data['vid'], 'status' => 1, 'is_check' => 1, 'is_delete' => 0])->field('id,uid')->find();
            if (empty($info)) exception('找不到视频记录!');
            if ($this->where(['id' => $info['id']])->inc('views', 1)) {
                (new UserVideoProfit())->updateProfit(['uid' => $info['uid'], 'type' => 5]);
                return true;
            }
            return false;
        } catch (\Exception $e) {
            if (stristr($e->getMessage(), 'SQLSTATE')) {
                $this->error = '数据走丢了，请稍后再试！';
            } else $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 获取分享页面信息
     * @param $id  视频id
     * @return array default_discount_price,title,share
     */
    public function getShareInfo($id)
    {
        try {
            if (empty($id)) exception('找不到该视频!');
            $ret = $this->alias('v')->join('user u', 'u.id=v.uid', 'left')->where(['v.id' => $id, 'v.is_check' => 1, 'v.status' => 1, 'v.is_delete' => 0])->field('v.title,v.cover,u.id as uid,u.nickname,u.avatarurl,u.invite_code')->find();
            return $ret ? $ret->toArray() : [];
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * 随机打乱排序
     */
    public function sortType($type = 0)
    {
        $where = [
            'is_check' => 1,
            'status' => 1,
            'is_delete' => 0
        ];
        if ($type == 0) {
            $where['is_hot'] = 1;
        } else {
            $where['type_id'] = $type;
        }
        $listLen = $this->where($where)->count();
        $list = $this->where($where)->limit(rand(0, (int)floor(($listLen - 1) / 3)), rand((int)floor(($listLen - 1) / 3), (int)floor(($listLen - 1) / 2)))->field('id,sort')->select();
        $len = count($list);
        $count = 0;
        if ($list && $len > 1) {
            $k = 0;
            foreach ($list as $v) {
                $v->sort = rand(1, $len + 100) + 0;
                if ($k % 2 == 0) {
                    $limit = $this->where('id', $v->id)->update([
                        'sort' => rand(1, $len + 100) + 0
                    ]);
                }
                $newList[] = $v;
                $count += $limit;
                $k++;
            }
        }
        return [$len, $count];
    }
}